package com.ruoyi.house.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.house.domain.Community;
import com.ruoyi.house.domain.MfDistrict;
import com.ruoyi.house.mapper.CommunityMapper;
import com.ruoyi.house.mapper.MfDistrictMapper;
import com.ruoyi.house.strategy.DataMaskUtil;
import com.ruoyi.house.vo.RgionVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.house.mapper.HouseMapper;
import com.ruoyi.house.domain.House;
import com.ruoyi.house.service.IHouseService;

/**
 * 房源信息Service业务层处理
 * 
 * @author yuanrui
 * @date 2025-07-25
 */
@Slf4j
@Service
public class HouseServiceImpl implements IHouseService 
{
    @Autowired
    private HouseMapper houseMapper;


    @Autowired
    private MfDistrictMapper districtMapper;

    @Autowired
    private CommunityMapper communityMapper;

    /**
     * 查询房源信息
     * 
     * @param id 房源信息主键
     * @return 房源信息
     */
    @Override
    public House selectHouseById(Long id)
    {
        return houseMapper.selectHouseById(id);
    }

    /**
     * 查询房源信息列表
     * 
     * @param house 房源信息
     * @return 房源信息
     */
    @Override
    public List<House> selectHouseList(House house)
    {
        List<House> houseList = houseMapper.selectHouseList(house);
        try {
            DataMaskUtil.maskList(houseList);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return houseList;
    }

    /**
     * 新增房源信息
     * 
     * @param house 房源信息
     * @return 结果
     */
    @Override
    public int insertHouse(House house)
    {
        house.setCreateTime(DateUtils.getNowDate());
        return houseMapper.insertHouse(house);
    }

    /**
     * 修改房源信息
     * 
     * @param house 房源信息
     * @return 结果
     */
    @Override
    public int updateHouse(House house)
    {
        house.setUpdateTime(DateUtils.getNowDate());
        return houseMapper.updateHouse(house);
    }

    /**
     * 批量删除房源信息
     * 
     * @param ids 需要删除的房源信息主键
     * @return 结果
     */
    @Override
    public int deleteHouseByIds(Long[] ids)
    {
        return houseMapper.deleteHouseByIds(ids);
    }

    /**
     * 删除房源信息信息
     * 
     * @param id 房源信息主键
     * @return 结果
     */
    @Override
    public int deleteHouseById(Long id)
    {
        return houseMapper.deleteHouseById(id);
    }

    @Override
    public List<RgionVo> buildRegionTree(List<MfDistrict> districts, List<Community> communities) {
        //验证数据
        validateData(districts, communities);

        //转换为Map结构
        Map<Long, MfDistrict> districtMap = districts.stream()
                .collect(Collectors.toMap(MfDistrict::getDistrictId, Function.identity()));

        //按pid分组
        Map<Long, List<MfDistrict>> districtGroup = districts.stream()
                .collect(Collectors.groupingBy(MfDistrict::getPid));

        //按区县id分组
        Map<Long, List<Community>> communityMap = communities.stream()
                .collect(Collectors.groupingBy(Community::getDistrictId));


        //查找根节点
        List<MfDistrict> rootDistrict = districts.stream()
                .filter(d -> d.getPid() == null ||
                        d.getPid() == 0 || d.getLevel() == 1)
                .collect(Collectors.toList());

        if(rootDistrict.isEmpty()){
            log.warn("未查询到根节点");
            return Collections.emptyList();
        }

        //构建树形结构

        return  rootDistrict.stream()
                .map(root -> buildNode(root, districtMap, districtGroup, communityMap))
                .collect(Collectors.toList());
    }


    @Override
    public List<RgionVo> getCommunityAndCityList() {

        // 1. 查询所有地区数据（省市区）
        List<MfDistrict> districts = districtMapper.selectList(
                Wrappers.<MfDistrict>query()
                        .select("district_id as districtId", "pid", "district", "level")
                        .in("level", Arrays.asList(1, 2, 3))
                        .orderByAsc("level", "pid")
        );

        if(districts.isEmpty()){
                log.warn("未查询到地区数据");
                return Collections.emptyList();
        }


        // 2. 查询所有社区数据
        List<Community> communities = communityMapper.selectList(
                Wrappers.<Community>query()
                        .select("id", "name", "district_id as districtId")
                        .orderByAsc("district_id")
        );

        log.info("地区数据量: {}, 社区数据量: {}", districts.size(), communities.size());

        //构建树形结构
        List<RgionVo> tree = buildRegionTree(districts, communities);


        if(tree.isEmpty()){
            log.warn("未查询到地区数据");
        }

        return tree;
    }





    private RgionVo buildNode(MfDistrict region,
                              Map<Long, MfDistrict> districtMap,
                              Map<Long, List<MfDistrict>> regionPidMap,
                              Map<Long, List<Community>> communityMap) {
        RgionVo node = convertToVo(region);

        // 添加子地区
        List<MfDistrict> children = regionPidMap.getOrDefault(region.getDistrictId(), Collections.emptyList());
        node.setChildren(
                children.stream()
                        .map(child -> buildNode(child, districtMap, regionPidMap, communityMap))
                        .collect(Collectors.toList())
        );

        // 如果是区县（level=3），添加社区
        if (region.getLevel() == 3) {
            List<Community> communities = communityMap.getOrDefault(region.getDistrictId(), Collections.emptyList());
            communities.forEach(community -> {
                RgionVo communityNode = new RgionVo();
                communityNode.setId(community.getId()); // 社区ID用负数
                communityNode.setName(community.getName());
                communityNode.setIsCommunity(true);
                communityNode.setCommunityId(community.getId());
                node.getChildren().add(communityNode);
            });
        }
        return node;
    }





    private RgionVo convertToVo(MfDistrict region) {
        RgionVo vo = new RgionVo();
        vo.setId(region.getDistrictId());
        vo.setPid(region.getPid());
        vo.setName(region.getDistrict());
        vo.setLevel(region.getLevel());
        vo.setIsCommunity(false); // 标记为地区节点
        vo.setChildren(new ArrayList<>()); // 初始化子节点列表
        return vo;
    }




    private void validateData(List<MfDistrict> regions, List<Community> communities) {
        // 1. 检查地区数据是否为空
        if (regions == null || regions.isEmpty()) {
            log.warn("地区数据为空");
            return;
        }

        // 2. 检查社区数据是否为空（只是警告，不影响继续执行）
        if (communities == null || communities.isEmpty()) {
            log.warn("社区数据为空，将只构建地区树");
        }

        // 3. 检查社区关联的区县是否存在
        Set<Long> districtIds = regions.stream()
                .filter(r -> r.getLevel() == 3) // 只检查level=3的区县
                .map(MfDistrict::getDistrictId)
                .collect(Collectors.toSet());

        long unlinkedCommunities = communities.stream()
                .filter(c -> !districtIds.contains(c.getDistrictId()))
                .count();

        if (unlinkedCommunities > 0) {
            log.warn("存在 {} 个社区没有关联到有效的区县（level=3）", unlinkedCommunities);
        }

        // 4. 检查地区父子关系
        Set<Long> allDistrictIds = regions.stream()
                .map(MfDistrict::getDistrictId)
                .collect(Collectors.toSet());

        long invalidParentRefs = regions.stream()
                .filter(r -> r.getPid() != null && r.getPid() != 0 && !allDistrictIds.contains(r.getPid()))
                .count();

        if (invalidParentRefs > 0) {
            log.warn("存在 {} 个地区引用了不存在的父ID", invalidParentRefs);
        }
    }
}
